import WebHeader from '@/www/components/WebHeader'
import WebFooter from '@/www/components/WebFooter'
import { loginByApiKey } from '@/apiv2/user'
import { getChargeTypes,postCharges,checkChargeIsPaid } from '@/apiv2/charge'
import { Loading } from 'element-ui';

export default {
  components: { WebHeader, WebFooter },
  data() {
    return {
      user: undefined,
      chargeTypeId: undefined,
      chargeTypes: [],
      payLoading: false,
      chargeId: undefined,
    }
  },

  created(){
    this.login()
    this.getChargeTypes()
  },

  methods: {
    login(){
      loginByApiKey().then(res => {
        this.user = res.user
      })
    },
    getChargeTypes(){
      getChargeTypes().then(res => {
        this.chargeTypes = res.charge_types
        this.chargeTypeId = res.charge_types[0].id
      })
    },
    pay(){
      let that = this
      this.payLoading = true
      postCharges({
        charge_type_id: this.chargeTypeId
      }).then(res => {
        this.payLoading = false
        this.chargeId = res.charge_id
        this.$alert('<img src="https://api.qrserver.com/v1/create-qr-code/?data=' + res.code_url +'" />', '请用微信扫码支付', {
          dangerouslyUseHTMLString: true,
          showConfirmButton: false,
          center: true
        })

        setInterval(function(){
          that.checkChargeIsPaidPerSecond()
        },2000)

      })
    },
    checkChargeIsPaidPerSecond(){
      checkChargeIsPaid(this.chargeId).then(res => {
        if (res.paid) {
         this.$router.go(0)
        }
      })
    }
  }
}
